package com.nstskj.study.netty.tcp.netty.protocol.handler.msg.impl;

import cn.hutool.core.collection.CollUtil;
import com.nstskj.study.netty.tcp.netty.protocol.endpoint.base.AbstractEndpoint;
import com.nstskj.study.netty.tcp.netty.protocol.endpoint.data.EndpointData;
import com.nstskj.study.netty.tcp.netty.protocol.enums.IotDeviceProtocolCmdEnum;
import com.nstskj.study.netty.tcp.netty.protocol.handler.msg.AbstractProtocolHandler;
import com.nstskj.study.netty.tcp.netty.protocol.message.in.msg.DeviceEndpointPushCmdMsg;
import com.nstskj.study.netty.tcp.netty.protocol.message.out.msg.DeviceEndpointPushOutputNetTcpMessage;
import com.nstskj.study.netty.tcp.netty.protocol.session.base.AbstractSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/20 21:07
 * @Description 设备注册消息处理者
 */
@Slf4j
@Component
public class DeviceEndpointPushHandler extends AbstractProtocolHandler<DeviceEndpointPushCmdMsg, DeviceEndpointPushOutputNetTcpMessage> {

    @Override
    public short supportCmd() {
        return (short) IotDeviceProtocolCmdEnum.DEVICE_ENDPOINT_PUSH.getCmd();
    }

    /**
     * 真正的协议处理 ，之类需要自己实现
     *
     * @param abstractInputNetTcpMessage
     * @param session
     * @return
     */
    @Override
    public DeviceEndpointPushOutputNetTcpMessage doHandlerCmdMsg(DeviceEndpointPushCmdMsg abstractInputNetTcpMessage, AbstractSession session) {
        //得到上传的端点数据
        List<EndpointData> endpointDataList = abstractInputNetTcpMessage.getEndpointDataList();
        DeviceEndpointPushOutputNetTcpMessage deviceEndpointPushOutputNetTcpMessage = new DeviceEndpointPushOutputNetTcpMessage();
        final List<EndpointData> dataList = new ArrayList<>();
        deviceEndpointPushOutputNetTcpMessage.setEndpointDataList(dataList);
        if (CollUtil.isNotEmpty(endpointDataList)) {
            endpointDataList.forEach(endpointData -> {
                short address = endpointData.getAddress();
                EndpointData result = new EndpointData();
                result.setAddress(address);
                AbstractEndpoint endpointByAddress = session.getEndpointByAddress(address);
                if (endpointByAddress != null && (!endpointByAddress.isOut())) {
                    //写入到端点的队列
                    endpointByAddress.addEndpointData(endpointData);
                    result.setHexStr("00");
                } else {
                    result.setHexStr("01");
                }
                dataList.add(result);
            });
        }
        return deviceEndpointPushOutputNetTcpMessage;
    }
}
